﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using DomainModel;
using NHibernate.Criterion;

namespace DAL
{
    public class NHibernateSample
    {
        private ISession _session;

        public ISession Session
        {
            set
            {
                _session = value;
            }
        }

        public NHibernateSample(ISession session)
        {
            _session = session;
        }

        public Unit GetUnitById(int unitId)
        {
            return _session.Get<Unit>(unitId);
        }

        public IList<Unit> From()
        {
            //返回所有Customer 类的实例
            return _session.CreateQuery("from Unit").List<Unit>();

        }

        public IList<string> Select()
        {
            //返回所有Customer 的CustomerId
            return _session.CreateQuery("select c.Name from Unit c order by c.Name asc").List<string>();
        }

        public IList<object[]> SelectObject()
        {
            return _session.CreateQuery("select c.Name, count(c.Name) from Unit c group by c.Name").List<object[]>();
        }

        public IList<Unit> Where()
        {
            return _session.CreateQuery(" from Unit c where c.Name='公斤' ").List<Unit>();
        }


        public IList<Unit> GetCustomersByFirstname(string firstname)
        {

            //写法3:命名型参数(推荐)
            return _session.CreateQuery(" from Unit c where c.Name=:fn").SetString("fn", firstname).List<Unit>();
        }

        public IList<Unit> CreateCriteria()
        {
            ICriteria crit = _session.CreateCriteria(typeof(Unit))
                                                                   .Add(Restrictions.Like("Name","公斤"))
                                                                   //.Add(Restrictions.Like("Firstname", "YJing%"))                                                                   
                                                                   ;
            crit.SetMaxResults(50);
            IList<Unit> customers = crit.List<Unit>();
            return customers;
        }

        public int CreateUnit(Unit unit)
        {
            int newid = (int)_session.Save(unit);
            _session.Flush();
            return newid;
        }

        public void DeleteUnit(Unit unit)
        {
            _session.Delete(unit);
            _session.Flush();
        }
    }
}
